package com.jsmile.cloud.tradecenter.order.listener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.jsmile.cloud.accountcenter.api.enums.PayTypeEnum;
import com.jsmile.cloud.accountcenter.api.feign.MemberServiceApi;
import com.jsmile.cloud.accountcenter.api.req.ReqMemberDetial;
import com.jsmile.cloud.accountcenter.api.res.ResMember;
import com.jsmile.cloud.msgcenter.api.feign.PayOrderServiceApi;
import com.jsmile.cloud.msgcenter.api.req.ReqPayOrderCreate;
import com.jsmile.cloud.tradecenter.api.exception.TradeException;
import com.jsmile.cloud.tradecenter.order.event.OrderCreateEvent;
import com.jsmile.mall.api.JSmileResult;
import com.jsmile.mall.cache.kit.SpringKit;

import lombok.extern.slf4j.Slf4j;

/**
 * 订单创建-创建支付订单
 */
@Slf4j
@Component
public class CreatePayOrderListener {

    @Order
    @EventListener(OrderCreateEvent.class)
    public void orderStatusChange(OrderCreateEvent event) {
        log.info("创建支付订单：{}", event.getOrder());
        SpringKit.getBean(PayOrderServiceApi.class).create(createPayOrders(event.getOrder()));
    }

    private ReqPayOrderCreate createPayOrders(com.jsmile.cloud.tradecenter.order.model.Order order) {
        ReqPayOrderCreate reqPayOrderCreate = ReqPayOrderCreate.builder().payType(order.getPayMethod()).build();
        JSmileResult<ResMember> resMember = SpringKit.getBean(MemberServiceApi.class).getMember(ReqMemberDetial.builder().userId(order.getUserId()).build());
        if (!resMember.getResSuccess()) {
            throw new TradeException(resMember.getResCode(), resMember.getResMsg(), null);
        }
        if (PayTypeEnum.WX_JS.getValue() == reqPayOrderCreate.getPayType()) {
            reqPayOrderCreate.setOpenId(resMember.getResData().getOpenId());
        } else if (PayTypeEnum.WX_H5.getValue() == reqPayOrderCreate.getPayType()) {
            reqPayOrderCreate.setOpenId(resMember.getResData().getAppOpenId());
        }
        ReqPayOrderCreate.PayOrderInfo payOrderInfo = new ReqPayOrderCreate.PayOrderInfo();
        payOrderInfo.setOrderNo(order.getId());
        payOrderInfo.setActuallyPayAmount(order.getActuallyPayAmount());
        payOrderInfo.setTitle(StringUtils.deleteWhitespace(order.getOrderProducts().get(0).getProductName()));
        reqPayOrderCreate.setPayOrderInfos(Lists.newArrayList(payOrderInfo));
        return reqPayOrderCreate;
    }
}
